package hnapay

import (
    "time"
	"encoding/json"
	"github.com/astaxie/beego"
)

type RefundContent struct {
	MerOrderId    string   `json:"merOrderId"`    //商户退款订单号
    OldMerOrderId string   `json:"oldMerOrderId"` //原商户支付请求订单号
    //OldDealId     string   `json:"oldDealId"`     //原商户网关支付订单号
    Amount        int      `json:"amount"`        //退款金额
    Currency      string   `json:"currency"`      //退款币种
    NoticeUrl     string   `json:"noticeUrl"`     //通知地址
}

type RefundReq struct {
	Header  *MsgHead       `json:"head,omitempty"`
	Content *RefundContent `json:"content,omitempty"`
	Sign    string         `json:"sign,omitempty"`
}

type RefundRspContent struct {
	ResponseCode   string  `json:"responseCode"`   //应答码
	ResponseDesc   string  `json:"responseDesc"`   //应答描述
	MerOrderId     string  `json:"merOrderId"`     //商户订单号
    OldMerOrderId  string  `json:"oldMerOrderId"`  //原商户支付请求订单号
    OldDealId      string  `json:"oldDealId"`      //原商户网关支付订单号
    RefundOrderNo  string  `json:"refundOrderNo"`  //系统退款订单号
    OldOrderAmount string  `json:"oldOrderAmount"` //原网关订单金额
    RefundAmount   string  `json:"refundAmount"`   //退款金额
    RefundFee      string  `json:"refundFee"`      //退款手续费
    Currency       string  `json:"currency"`       //退款币种
    FeeCurrency    string  `json:"feeCurrency"`    //退款币种
	Status         string  `json:"status"`         //退款状态
    CompleteTime   string  `json:"completeTime"`   //完成时间
}

type RefundRsp struct {
	Header  *MsgHead          `json:"head"`
	Content *RefundRspContent `json:"content"`
}

func Refunds(merCode,refundId,orderId string,amount int,currency string,noticeUrl,publicKey string)(rsp *RefundRsp, err error){
	var reqParams = new(RefundReq)
	msgHeader := new(MsgHead)
	msgHeader.SerCode = "101006"
	msgHeader.MerCode = merCode
	msgHeader.OrderId = refundId
	msgHeader.MerDate = time.Now().Format("20060102")  //yyyyMMdd
	msgHeader.MerTime = time.Now().Format("150405")    //hhmmss
	msgHeader.VersionNo = "2.0"
	msgHeader.SignType = "2"
	reqParams.Header = msgHeader
	//
	content := new(RefundContent)
	content.MerOrderId = refundId
	content.OldMerOrderId = orderId
	//content.OldDealId = oldDealId
	content.Amount = amount
	content.Currency = currency
	content.NoticeUrl = noticeUrl
	reqParams.Content = content
	if b, err := json.Marshal(reqParams); err == nil {
		reqParams.Sign = signMd5(string(b), publicKey)
	}
	var result string
	if b, err := json.Marshal(reqParams); err == nil { 
		result = base64Encode(b)
	}
	//
	rsp = new(RefundRsp)
	reqURL := "https://uwebgate.hnapay.com/webgate/unifiedAPI.htm"
	sdk := NewSDK(reqURL, merCode, publicKey)
	_, err = sdk.RefundRequest(result, rsp)
	if err != nil {
		beego.Debug("Hnapay Refund err:", err.Error())
		return
	}
	return
}

